package com.lht.oauth2.jdbc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lht.oauth2.jdbc.entity.*;
import com.lht.oauth2.jdbc.mapper.*;
import com.lht.oauth2.jdbc.service.ISysPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Eric
 * @since 2019-05-13
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysCompanyMapper sysCompanyMapper;

    @Autowired
    private SysCompanyRoleMapper sysCompanyRoleMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;


    @Override
    public List<SysPermission> findSysPermission(Long userId, Long companyId) {
        SysCompany company=sysCompanyMapper.selectOne(new QueryWrapper<SysCompany>()
                .eq("del_flag",1)
                .eq("id",companyId));
        if(null==company){
            return null;
        }

        List<SysCompanyRole> companyRoleList=sysCompanyRoleMapper.selectList(new QueryWrapper<SysCompanyRole>()
                            .eq("del_flag",1)
                            .eq("company_id",companyId));

        List<SysUserRole>  userRoleList=sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>()
                            .eq("del_flag",1)
                            .eq("user_id",userId));
        List<Long> roleIdList=new ArrayList<>();
        for(SysUserRole userRole:userRoleList){
            for(SysCompanyRole companyRole:companyRoleList){
                if(userRole.getRoleId().equals(companyRole.getRoleId())){
                    roleIdList.add(userRole.getRoleId());
                    break;
                }
            }
        }
        List<SysRolePermission> sysRolePermissionList=new ArrayList<>();
        for(Long roleId:roleIdList){
            sysRolePermissionList.addAll(sysRolePermissionMapper.selectList(new QueryWrapper<SysRolePermission>()
                                        .eq("del_flag",1)
                                        .eq("role_id",roleId)));
        }
        List<SysPermission> sysPermissionList=new ArrayList<>();
        for(SysRolePermission rolePermission:sysRolePermissionList){
            sysPermissionList.add(sysPermissionMapper.selectOne(new QueryWrapper<SysPermission>()
                                        .eq("del_flag",1)
                                        .eq("permission_id",rolePermission.getPermission())));
        }
        return sysPermissionList;
    }
}
